<?php

/**
 * Core helper functions.
 *
 * namespace spica\core\utils\functions
 *
 * @category   spica
 * @package    core
 * @subpackage utils
 * @author     Pham Cong Dinh <pcdinh at phpvietnam dot net>
 * @since      Version 0.2
 * @since      March 16, 2009
 * @copyright  Pham Cong Dinh (http://www.phpvietnam.net)
 * @license    http://www.gnu.org/licenses/lgpl-3.0.txt
 * @version    $Id: BaseUtils.php 1712 2010-02-23 18:16:42Z pcdinh $
 */

/**
 * Rotates values. E.x: odd and even rows
 *
 * <code>
 *   spica_rotate('odd', 'even');
 *   spica_rotate('one', 'two', 'three');
 * </code>
 *
 * @param  varargs List of rotated values If the argument list is emty then the rotation is reset
 * @return string
 */
function spica_rotate()
{
    static $index = 0;
    $values    = func_get_args();

    $value     = null;
    $length    = count($values);
    if (0      === $length)
    {
        $index = 0;
    }
    else
    {
        if (true    === isset($values[$index]))
        {
            $value  = $values[$index];
        }

        if ($length === $index + 1)
        {
            $index  = 0;
        }
        else
        {
            $index++;
        }
    }

    return $value;
}

/**
 * Given a file, i.e. /css/base.css, replaces it with a string containing the
 * file's mtime, i.e. /css/base.1221534296.css.
 *
 * In template file, use this
 * <code>
 * <link rel="stylesheet" href="<?php echo spica_auto_version('/css/base.css')?>" type="text/css" />
 * </code>
 *
 * In .htaccess, use this
 *
 * <code>
 * RewriteEngine on
 * RewriteRule ^(.*)\.[\d]+\.(css|js)$ $1.$2 [L]
 * </code>
 *
 * @param $file The file to be loaded. Must be an absolute path (i.e. starting with slash).
 */
function spica_auto_version($file)
{
    if (strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
    {
        return $file;
    }

    $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
    return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}

/**
 * Dumps the internal structure of a value into a human readable string.
 *
 * @param  mixed $var
 * @return string
 */
function spica_var_dump($var)
{
    // var_dump the variable into a buffer and keep the output
    ob_start();
    var_dump($var);
    $output = ob_get_clean();

    // neaten the newlines and indents
    $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);

    if (PHP_SAPI == 'cli')
    {
        $output = PHP_EOL.PHP_EOL.$output.PHP_EOL;
    }
    else
    {
        $output = '<pre>'.htmlspecialchars($output, ENT_QUOTES).'</pre>';
    }

    return $output;
}

/**
 * Dumps message and related contained information in the given exception
 * to HTML format to print out.
 *
 * @param  Exception $e
 * @return string
 */
function spica_exception_render(Exception $e)
{
    $hint = null;

    switch (get_class($e))
    {
        case 'Zend_Db_Statement_Exception':
            $trace = $e->getTrace();
            $hint = $trace[2]['args'][0];
            break;

        case 'PDOException':
            $trace = $e->getTrace();
            $hint = $trace[0]['args'][0];
            break;
    }

    if (PHP_SAPI === 'cli')
    {
        echo 'Exception: ', get_class($e), "\n";
        echo 'Message: ', $e->getMessage(), "\n";
        echo 'Source: ', $e->getFile(), ':', $e->getLine(), "\n";
        return true;
    }

    $showParams = $showFile = SpicaContext::isDebug();
    include_once SpicaContext::getBasePath().'/library/spica/core/templates/exception/general.tpl.php';
}

/**
 * Analyzes a trace line to extract useful information such as class name,
 * function name, call and ther others and return as a string.
 *
 * @param  array $traceElt
 * @param  bool  $param
 * @return string
 */
function spica_exception_trace_stringify($traceElt, $param = false)
{
    $info  = array_key_exists('class', $traceElt) ? $traceElt['class'] . $traceElt['type'] : '';
    $info .= $traceElt['function'];
    $info .= '(';

    if (true === isset($traceElt['args']))
    {
        $count  = count($traceElt['args']);
        for ($i = 0; $i < $count; $i++)
        {
            $arg   = $traceElt['args'][$i];
            $info .= is_object($arg) ? get_class($arg) : gettype($arg);

            if ($i < $count - 1)
            {
                $info .= ', ';
            }
        }
    }

    $info .= ')';

    if (isset($traceElt['args']) && true === $param)
    {
        $info .= spica_var_dump($traceElt['args'], 'func_get_args(): ', false);
    }

    return $info;
}

?>